import itchat
from openpyxl import Workbook
from openpyxl import styles as sty
from openpyxl.styles import Alignment
from openpyxl.styles import Font, colors, Border, Side
from pyecharts import Pie


class wxBot:
    def __init__(self):
        wxBot.login(self)

    def login(self):
        itchat.auto_login(
            hotReload=True, statusStorageDir='itchat.pkl')

    def logout(self):
        itchat.logout()

    def save_xsl(self):
        friends = itchat.get_friends()[1:]  # list第一项是本人信息 需要跳过
        wb = Workbook()
        ws = wb.active
        ws.append(['姓名', '性别', '城市', '签名', '备注'])

        for row in range(2, len(friends)+2):
            if friends[row-2]['Sex'] == 1:
                Sex = "男"
            elif friends[row-2]['Sex'] == 2:
                Sex = "女"
            else:
                Sex = "未知"
            ws['A' + str(row)] = friends[row-2]['NickName']
            ws['B' + str(row)] = Sex
            ws['C' + str(row)] = friends[row-2]['City']
            ws['D' + str(row)] = friends[row-2]['Signature']
            ws['E' + str(row)] = friends[row-2]['RemarkName']

        # 合并单元格
        lastRow = str(len(friends) + 2)
        ws.merge_cells('B' + lastRow + ':I' + lastRow)
        # 通用边框信息
        left, right, top, bottom = [Side(style='medium', color='000000')] * 4
        border = Border(left=left, right=right, top=top, bottom=bottom)

        # 设置单元格边框和颜色
        # 表头和最后一行的说明使用默认的黑色
        if row == 1:
            ws[str()].font = Font()
        for row in range(1, len(friends) + 2):
            # 奇偶行字体颜色交替
            if row % 2 == 0:
                color = 'D98719'
            else:
                color = '00CCFF'
            if row == 1:
                color = '000000'
            # 设置边框和颜色
            for col in 'ABCDE':
                ws[col + str(row)].border = border
                if row == 1:
                    ws[col + str(row)].alignment = Alignment(
                        horizontal='center', vertical='center')
                    ws[col + str(row)].font = Font('宋体',
                                                   color=color, size=18, bold=True)
                    # 首行背景颜色：紫色（4b0091）
                    ws[col + str(row)].fill = sty.PatternFill(
                        fill_type='solid', fgColor="4b0091")
                else:
                    if row % 2 == 0:
                        ws[col + str(row)].font = Font(color=color, size=15)
                        ws[col + str(row)].fill = sty.PatternFill(
                            fill_type='solid', fgColor="01814a")
                    else:
                        ws[col + str(row)].font = Font('宋体',
                                                       color=color, size=15)
                        ws[col + str(row)].fill = sty.PatternFill(
                            fill_type='solid', fgColor="ce0000")
                if col == "D":
                    ws.column_dimensions['D'].width = 60
                if col == "E":
                    ws.column_dimensions['E'].width = 25
        # 保存文件
        wb.save('friendslist.xlsx')
        print('打印成功！')

    def watch_chat(self):
        chats_list = itchat.get_chatrooms()
        itchat.search_chatrooms('')
        print("群组信息如下：")
        for i in range(0, len(chats_list)):
            print(i, chats_list[i]['NickName'])
        pos = int(input("输入序号,选择群聊："))
        try:
            chat = chats_list[pos]['UserName']
        except IndexError:
            print('\n输入的群组标号有误，请确认群组标号后，重新选择！\n\n\n')
            return
        text = input("请输入你要发送的文字：")
        pic = input("请输入你要发送的图片：")
        itchat.send_msg(text, chat)
        itchat.send_image(pic, chat)

    def talk(self):
        nickname = input(u'请输入好友昵称或备注: ')
        try:
            getUserJson = itchat.search_friends(name=nickname)
            getUserName = getUserJson[0]['UserName']
        except IndexError:
            print('\n没有此好友，请重新输入联系人昵称或备注！\n\n\n')
            return
        msg = input(u'请输入你要和他说的话：')
        itchat.send(msg, toUserName=getUserName)

    def create_html(self):
        friends = itchat.get_friends()[1:]  # list第一项是本人信息 需要跳过
        city_list = []
        for i in friends:
            if i['City']:
                city_list.append(i['City'])
        city = set(city_list)
        num = []
        for c in city:
            num.append(city_list.count(c))
        pie = Pie("不同城市好友分布饼图", height=500, width=1300, title_top=10)
        pie.add("", city, num, is_label_show=True,
                legend_orient="vertical", legend_pos="50", legend_top="50")
        pie.render("city.html")
        print("图表生成成功")
